<template lang="html">
  <div class="header-loading">
    <div class="wrapper">
      <div class="bita-icon" @click="linkTo('/')"></div>
      <div class="nav">
        <a class="item" @click="linkTo('/')">首页</a>
        <a class="item" @click="linkTo('/landingprice')">价格</a>
        <a class="item" :href="helpDocumentUrl" target="_blank">帮助文档</a>
      </div>
      <div class="logon-status" v-if="!userInfo.token">
        <a class="logon-signup" @click="logon('in')">登录</a>
        <el-button class="logon-signin" type="primary" round @click="logon('up')">注册</el-button>
      </div>
      <div class="avatar" v-else>
        <el-popover
          placement="bottom-end"
          width="417"
          trigger="hover"
          popper-class="headermovepopper"
          v-model="popoverVisible">
          <div class="header-popover">
            <div class="pop-header">
              <div class="pop-header-left">
                <!-- <img class="pop-avatar" :src="userInfo.headImage" /> -->
                <div>
                  <p><span>{{nickname}}</span> @{{accoutname}}</p>
                  <!-- <p class="userinfo-email">{{userInfo.email}}</p> -->
                </div>
              </div>
              <div class="pop-header-right">
                <button @click="toModifyInfo">修改资料</button>
              </div>
            </div>
            <div class="pop-team">
              <ul class="pop-team-wrap">
                <li class="pop-team-ico">
                    <img src="@/common/image/team-all-ico.png" alt="">
                </li>
                <li class="pop-team-item" v-for="(item, index) in teamDataSet" :key="index" @click="goTeamHomeFun(item.teamId,item.role)">{{item.teamName}}</li>
                <li class="pop-team-add" v-if="!hiddenCreate" @click="linkTo('/teamadd')">
                  + 创建团队
                </li>
              </ul>
            </div>
            <div class="line"></div>
            <div class="pop-order">
              <div class="pop-calc">
                <div class="pop-calc-left">
                  <img class="order-icon" src="@/common/image/icon/icon-suanli.png" />
                  <p>可用算力：<span class="num-lan">{{powerSur}}</span></p>
                </div>
                <div class="pop-calc-right">
                  <button @click="linkTo('/order')">算力充值</button>
                </div>
              </div>
              <div class="pop-storage">
                <img class="order-icon" src="@/common/image/icon/icon-cuncu.png" />
                <p>可用存储：<span class="num-lan">{{storageTotal - storageUsed}}GB</span> <span>共{{storageTotal}}GB</span></p>
              </div>
            </div>
            <div class="line"></div>
            <div class="pop-nav">
              <div class="pop-nav-item nav-user" @click="linkTo('/index')">
                <p>个人中心</p>
              </div>
              <div class="pop-nav-item nav-price" @click="linkTo('/personalmirror')">
                <p>我的镜像</p>
              </div>
              <div class="pop-nav-item nav-price" @click="toCostCenter">
                <p>费用中心</p>
              </div>
              <div class="pop-nav-item nav-calc" @click="linkTo('/order/list')">
                <p>算力明细</p>
              </div>
            </div>
            <div class="line"></div>
            <div class="pop-footer">
              <span @click="_logOut">退出当前账户</span>
            </div>
          </div>
          <img
            slot="reference"
            class="avatar-item"
            :src="userInfo.headImage"
            alt="avatar" />
        </el-popover>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
import { getUserCalculationPower, queryStorage, getOrderStorageCountByUserId } from '@/api/order'
import { getUserNickname } from '@/api/loginout'
import { getTeamList } from '@/api/team_list'
import { logOut, checkToken } from '@/api/user'
import store from '@/store'
import qs from 'qs'

export default {
  name: 'headerLoading',
  data () {
    return {
      // 帮助文档地址
      helpDocumentUrl: `${process.env.VUE_APP_HELP}/help/index.html`,
      // 用户信息显示
      popoverVisible: false,
      // 用户昵称
      nickname: '',
      accoutname: '',
      teamDataSet: [],
      hiddenCreate: false,
      // 可用算力
      powerSur: 0,
      // 总存储
      storageTotal: 0,
      // 已用存储
      storageUsed: 0
    }
  },
  methods: {
    // 打开新页面
    toModifyInfo () {
      this.popoverVisible = false
      window.open(`${process.env.VUE_APP_BITA_EDIT_INFO}?token=${this.userInfo.bitaToken}`)
    },
    // 打开费用中心
    toCostCenter () {
      this.popoverVisible = false
      window.open(`${process.env.VUE_APP_BITA_COST_CENTER}?token=${this.userInfo.bitaToken}`)
    },
    // 跳转
    linkTo (path) {
      this.$router.push({ path })
    },
    goTeamHomeFun (teamid, role) {
      if (this.$route.path === '/team/detail/member' || this.$route.path === '/team/detail/count') {
        this.$router.push({ path: '/team/detail/member', query: { id: teamid, role: role } })
        this.reload()
      } else {
        this.$router.push({ path: '/team/detail/member', query: { id: teamid, role: role } })
        this.reload()
      }
    },
    // 注册 / 登录
    logon (state) {
      if (state === 'up') {
        window.open(`${process.env.VUE_APP_BITA_REGISTER}`)
      } else if (state === 'in') {
        this.$router.push({ path: '/login' })
      }
    },
    queryData () {
      this._getAvailablePower()
      this._getUserNickname()
      this._getStorageInfo()
      this._getTeamList()
      this._getOrderStorageCountByUserId()
    },
    /*
      -----接口调用-----
    */
    // 验证用户token是否有效
    _checkToken () {
      checkToken().then(res => {
        if (res.message.code === 0) {
          this.queryData()
        } else {
          store.commit('LOG_OUT')
        }
      })
    },
    // 退出
    _logOut () {
      logOut().then(res => {
        if (res.message.code === 0) {
          this.setLogOut()
          this.$router.push({ 'path': '/' })
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 查询可用算力
    _getAvailablePower () {
      const query = `?token=${this.userInfo.bitaToken}`
      getUserCalculationPower(query).then(res => {
        if (res.code === 0) {
          this.powerSur = res.result.surplusCalculationPower.toFixed(1)
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 查询昵称
    _getUserNickname () {
      const query = `?token=${this.userInfo.bitaToken}`
      getUserNickname(query).then(res => {
        if (res.code === 0) {
          this.nickname = res.result.username
          this.accoutname = res.result.account
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 查询全部团队名称
    _getTeamList () {
      getTeamList().then(res => {
        if (res.message.code === 0) {
          this.teamDataSet = res.data.teamList
          this.hiddenCreate = res.data.createTeam
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 查看存储详情
    _getStorageInfo () {
      const query = `?token=${this.userInfo.bitaToken}`
      queryStorage(query).then(res => {
        if (res.code === 0) {
          this.storageUsed = res.result.storageSize.toFixed(1)
          this._getOrderStorageCountByUserId()
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 查询总存储空间
    _getOrderStorageCountByUserId () {
      const data = qs.stringify({
        token: this.userInfo.bitaToken
      })
      getOrderStorageCountByUserId(data).then(res => {
        if (res.code === 0) {
          this.storageTotal = res.result.toFixed(1)
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    ...mapMutations({
      setLogOut: 'LOG_OUT'
    })
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  mounted () {
    if (this.$route.path !== '/jointeam') {
      if (this.userInfo && this.userInfo.token) {
        this._checkToken()
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.header-loading
  width 100%
  background #ffffff
  .wrapper
    width 1100px
    margin 0 auto
    padding 36px 0 30px 0
    display flex
    .bita-icon
      flex 0 0 182px
      height 32px
      background url(../../common/image/icon-bita.png) no-repeat left center
      background-size 108px 22px
      cursor pointer
      &:hover
        background url(../../common/image/icon-bita-active.png) no-repeat left center
        background-size 108px 22px
    .nav
      flex 1
      font-size 0
      .item
        display inline-block
        height 32px
        line-height 32px
        padding-right 26px
        font-size 16px
        color #4D9DFF
        &:hover
          color #1c83da
    .logon-status
      flex 0 0 152px
      color #4D9DFF
      .logon-signup
        display inline-block
        width 76px
        height 32px
        line-height 32px
        font-size 16px
        color #4D9DFF
        border-radius 28px
        text-align center
        vertical-align top
        &:hover
          color #1c83da
      .logon-signin
        width 76px
        padding 8px 0
        border-radius 0
    .avatar
      flex 0 0 26px
      img
        width 26px
        height 26px
        border-radius 50%
        cursor pointer
.header-popover
  .pop-team
    padding 0 40px 25px
    .pop-team-wrap
      display flex
      flex-wrap wrap
      align-items center
      .pop-team-ico
        width 22px
        height 22px
        margin-right 7px
        img
          width 22px
          height 22px
      .pop-team-item
        font-size 14px
        color #6e6e6e
        line-height 20px
        margin-right 9px
        cursor pointer
      .pop-team-add
        font-size 14px
        line-height 20px
        color #2196F3
        padding-left 2px
        cursor pointer
  .pop-header
    padding 32px 17px 17px 40px
    display flex
    justify-content space-between
    align-items center
    .pop-header-left
      display flex
      p
        font-size 14px
        color #8D9091
        line-height 20px
      p:nth-of-type(1)
        padding-bottom 4px
        span
          font-size 16px
          font-weight bold
          line-height 22px
          color #2D323B
          margin-right 6px
      .pop-avatar
        width 42px
        height 42px
        border-radius 50%
        margin-right 20px
      .userinfo-email
        color #8c94a0
    .pop-header-right
      >button
        border-radius 14px
        background #F4F7F8
        border none
        color #2D323B
        font-size 14px
        line-height 20px
        padding 4px 17px
        cursor pointer
        outline none
  .pop-order
    padding 27px 23px 30px 40px
    .order-icon
      width 22px
      height 22px
      margin-right 8px
    .pop-calc
      display flex
      justify-content space-between
      align-items center
      .pop-calc-left
        display flex
        align-items center
        font-size 14px
        color #6E6E6E
        .num-lan
          font-size 16px
          color #39a1f4
      .pop-calc-right
        >button
          border none
          border-radius 14px
          color #2D323B
          font-size 14px
          line-height 20px
          padding 4px 17px
          background #F4F7F8
          cursor pointer
          outline none
    .pop-storage
      display flex
      align-items center
      padding-top 10px
      p>span
        font-size 14px
        color #909399
        margin-right 9px
      >p
        .num-lan
          font-size 16px
          color #39a1f4
  .pop-nav
    padding 30px 40px
    display flex
    font-size 14px
    line-height 20px
    color #6E6E6E
    justify-content space-around
    .pop-nav-item
      cursor pointer
  .pop-footer
    background #F4F7F8
    padding 16px 12px
    font-size 14px
    line-height 20px
    display flex
    justify-content center
    >span
      cursor pointer
  .line
    height 2px
    width 100%
    background #F4F4F4
</style>
